package com.css.zfzx.sjcj.modules.yhdisaster.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.ZipDownloadUtil;
import com.css.zfzx.sjcj.modules.boundary.service.BoundaryService;
import com.css.zfzx.sjcj.modules.boundary.viewobjects.BoundaryQueryParams;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.entity.YhDisasterEntity;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.entity.YhDisasterEvaluateVO;
import com.css.zfzx.sjcj.modules.yhdisaster.service.YhDisasterService;
import com.css.zfzx.sjcj.modules.yhdisaster.viewobjects.ExcelDataVo;
import com.css.zfzx.sjcj.modules.yhdisaster.viewobjects.RpheqVo;
import com.css.zfzx.sjcj.modules.yhdisaster.viewobjects.YhDisasterQueryParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lxg
 * @date 2020-11-10
 */
@Slf4j
@RestController
@RequestMapping("/yh/yhDisasters")
@Api(value = "重点隐患数据评估value" ,tags = {"重点隐患数据评估模块"})
public class YhDisasterController {
    @Autowired
    private YhDisasterService yhDisasterService;

    @GetMapping("/queryYhDisasters/{type}")
    public RestResponse queryYhDisasters(@PathVariable("type") String type, HttpServletRequest request, YhDisasterQueryParams queryParams) {
        RestResponse response = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            String sort=request.getParameter("sort");
            String order=request.getParameter("order");
            JSONObject jsonObject = yhDisasterService.queryYhDisasters(queryParams, curPage, pageSize, type, sort, order);
            response = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

//    @GetMapping("{id}")
//    public RestResponse getYhDisaster(@PathVariable String id) {
//        RestResponse response = null;
//        try {
//            YhDisasterEntity yhDisaster = yhDisasterService.getYhDisaster(id);
//            response = RestResponse.succeed(yhDisaster);
//        } catch (Exception e) {
//            String errorMessage = "获取失败!";
//            log.error(errorMessage, e);
//            response = RestResponse.fail(errorMessage);
//        }
//        return response;
//    }
    @GetMapping("{id}/{province}")
    public RestResponse getYhDisaster(@PathVariable String id,@PathVariable String province) {
        RestResponse response = null;
        try {
            response = RestResponse.succeed(yhDisasterService.getYhDisaster(id,province));
        } catch (Exception e) {
            String errorMessage = "获取失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    @PostMapping("{type}")
    public RestResponse saveYhDisaster(@PathVariable String type, @RequestBody YhDisasterEntity yhDisaster) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            yhDisasterService.saveYhDisaster(yhDisaster, type);
            json.put("message", "新增成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "新增失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;

    }

    /**
     * 修改数据
     *
     * @param yhDisaster
     * @return
     */
    @PutMapping
    public RestResponse updateYhDisaster(@RequestBody YhDisasterEntity yhDisaster) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            yhDisasterService.updateYhDisaster(yhDisaster);
            json.put("message", "修改成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "修改失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 批量删除数据
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public RestResponse deleteYhDisasters(@RequestParam List<String> ids) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            yhDisasterService.deleteYhDisasters(ids);
            json.put("message", "删除成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "删除失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 获取有效的字典项
     *
     * @param dictCode
     * @return
     */
    @GetMapping("/getValidDictItemsByDictCode/{dictCode}")
    public RestResponse getValidDictItemsByDictCode(@PathVariable String dictCode) {
        RestResponse restResponse = null;
        try {
            restResponse = RestResponse.succeed(yhDisasterService.getValidDictItemsByDictCode(dictCode));
        } catch (Exception e) {
            String errorMsg = "字典项获取失败!";
            log.error(errorMsg, e);
            restResponse = RestResponse.fail(errorMsg);
        }
        return restResponse;
    }

    /**
     * 导入
     *
     * @param file
     * @param response
     * @return
     */
    @PostMapping("/importDisaster")
    public RestResponse export(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        RestResponse restResponse = null;
        try {
            String s = yhDisasterService.exportExcel(file, response);
            restResponse = RestResponse.succeed(s);
        } catch (Exception e) {
            String errormessage = "导入失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

//    /***
//     * 提交数据
//     * @param ids
//     * @return
//     */
//    @PostMapping("/submit")
//    public RestResponse submitYhDisaster(@RequestBody String ids) {
//        RestResponse response = null;
//        JSONObject json = new JSONObject();
//        try {
//            yhDisasterService.submitYhDisaster(ids);
//            json.put("message", "修改成功!");
//            response = RestResponse.succeed(json);
//        } catch (Exception e) {
//            String errorMessage = "修改失败!";
//            log.error(errorMessage, e);
//            response = RestResponse.fail(errorMessage);
//        }
//        return response;
//    }
    /***
     * 提交数据
     * @param disasterEntities
     * @return
     */
    @PostMapping("/submit")
    public RestResponse submitYhDisaster(@RequestBody List<YhDisasterEntity> disasterEntities) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            yhDisasterService.submitYhDisaster(disasterEntities);
            json.put("message", "修改成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "修改失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /***
     * 导出
     * @param type
     * @param response
     * @return
     */
    @GetMapping("/exportFile/{type}")
    public RestResponse exportFileYhDisasters(@PathVariable("type") String type, HttpServletResponse response,
                                              @RequestParam(name = "yhCode", required = false) String yhCode, @RequestParam(name = "yhUnit", required = false) String yhUnit,
                                              @RequestParam(name = "yhProjectName", required = false) String yhProjectName, @RequestParam("yhProjectTask") String yhProjectTask,
                                              @RequestParam("province") String province, @RequestParam("city") String city, @RequestParam("area") String area,
                                              @RequestParam("yhConstructionScale") String yhConstructionScale, @RequestParam("yhEarthFortification") String yhEarthFortification,
                                              @RequestParam("yhFieldType") String yhFieldType, @RequestParam("yhLotType") String yhLotType, @RequestParam("evaluationResult") String evaluationResult,@RequestParam(required = false,value = "extends1")String extends1) {
        RestResponse responseRest = null;
        JSONObject jsonObject = new JSONObject();
        try {
            YhDisasterQueryParams queryParams = new YhDisasterQueryParams();
            if(!("null".equals(province) || StringUtils.isEmpty(province))){
                queryParams.setProvince(province);
            }
            if(!("null".equals(city) || StringUtils.isEmpty(city))){
                queryParams.setCity(city);
            }
            if(!("null".equals(area) || StringUtils.isEmpty(area))){
                queryParams.setArea(area);
            }
            if(!("null".equals(extends1) || StringUtils.isEmpty(extends1))){
                queryParams.setExtends1(extends1);
            }
            queryParams.setEvaluationResult(evaluationResult);
            queryParams.setYhCode(yhCode);
            queryParams.setYhConstructionScale(yhConstructionScale);
            queryParams.setYhEarthFortification(yhEarthFortification);
            queryParams.setYhFieldType(yhFieldType);
            queryParams.setYhLotType(yhLotType);
            queryParams.setYhProjectName(yhProjectName);
            queryParams.setYhProjectTask(yhProjectTask);
            queryParams.setYhUnit(yhUnit);
            yhDisasterService.exportFile(queryParams, type, response);
            jsonObject.put("message", "导出成功");
            responseRest = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            responseRest = RestResponse.fail(errorMessage);
        }
        return responseRest;
    }

    /**
     * 承灾体单体地震灾害隐患等级评估
     * @param type
     * @param queryParams
     * @return
     */
    @PostMapping("/assessmentInfo/{type}")
    public RestResponse assessmentInfo(@PathVariable("type") String type,
                                       @RequestBody YhDisasterQueryParams queryParams) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            yhDisasterService.assessmentInfo(type,queryParams);
            json.put("message", "评估成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "评估失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

//    /**
//     * 单条数据评估
//     * @param ids
//     * @return
//     */
//    @PostMapping("/evaluate")
//    public RestResponse autoAssessment(@RequestBody String ids) {
//        RestResponse response = null;
//        JSONObject json = new JSONObject();
//        try {
//            yhDisasterService.autoAssessment(ids);
//            json.put("message", "修改成功!");
//            response = RestResponse.succeed(json);
//        } catch (Exception e) {
//            String errorMessage = "修改失败!";
//            log.error(errorMessage, e);
//            response = RestResponse.fail(errorMessage);
//        }
//        return response;
//    }
    /**
     * 单条数据评估
     * @param vo
     * @return
     */
    @PostMapping("/evaluate")
    public RestResponse autoAssessment(@RequestBody YhDisasterEvaluateVO vo) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            yhDisasterService.autoAssessment(vo);
            json.put("message", "修改成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "修改失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }


    /**
     *  区域分类地震灾害隐患等级评估
     * @param rpheqVo
     * @return
     */
    @PostMapping("/rpheq")
    @ApiOperation(value = "隐患等级计算接口",notes = "功能备注（属性，方法类型）")
    public RestResponse evaluateRpheq(@ApiParam(name = "rpheqVo", value = "请求参数") @RequestBody RpheqVo rpheqVo) {
        Map<String, String> hazardLevelResult = yhDisasterService.evaluateRpheq(rpheqVo);
        if (hazardLevelResult.get("error") != null) {
            return RestResponse.succeed(hazardLevelResult.get("error"));
        } else {
            return RestResponse.succeed(hazardLevelResult);
        }
    }



    @Value("${file.boundary.path}")
    private String boundaryPath;
    @Autowired
    private BoundaryService boundaryService;
    @GetMapping("/download")
    public RestResponse downloadFile(RpheqVo rpheqVo, HttpServletResponse response) {
        //获取指定路径下的所有文件名
        File file = new File(boundaryPath);
        File[] files = file.listFiles();
        if (files == null) {
            return RestResponse.fail("下载失败，该目录下不存在文件");
        }
        String province = rpheqVo.getProvince(), city = rpheqVo.getCity(), area = rpheqVo.getArea();
        BoundaryQueryParams queryParams = new BoundaryQueryParams();
        queryParams.setProvince(province);
        queryParams.setCity(city);
        queryParams.setArea(area);
        List<String> codes = boundaryService.getDistrictNumber(queryParams);

        String zipFileName = "";
        List<File> zipFiles = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getName();
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            if (codes.indexOf(fileName) != -1) {
                zipFileName = fileName;
                zipFiles.add(files[i]);
            }
        }
        StringBuffer sb = new StringBuffer();
        if (!CollectionUtils.isEmpty(zipFiles)) {
            String zipName = zipFileName + ".zip";
            String msg = ZipDownloadUtil.zipDownload(response, boundaryPath, zipName, zipFiles);
            sb.append(msg);
            return null;
        } else {
            String zipName = "0.zip";
            String msg = ZipDownloadUtil.zipDownload(response, boundaryPath, zipName, new ArrayList<File>());
            return null;
        }
    }

    @GetMapping("/exportEvaluateRpheqResult")
    @ApiOperation(value = "隐患等级计算结果导出接口",notes = "功能备注（属性，方法类型）")
    public RestResponse exportEvaluateRpheqResult(RpheqVo rpheqVo, HttpServletResponse response) {
        try {
            yhDisasterService.exportEvaluateRpheqResult(rpheqVo, response);
        } catch (Exception e) {
            String errorMsg = "导出失败!";
            log.error(errorMsg, e);
        }
        return null;
    }

    @PostMapping("/searchEvaluateRpheqResult")
    @ApiOperation(value = "隐患等级计算结果查询接口",notes = "功能备注（属性，方法类型）")
    public RestResponse searchEvaluateRpheqResult(RpheqVo rpheqVo) {
        RestResponse response = null;
        try {
            List<ExcelDataVo> excelDataVos = yhDisasterService.searchEvaluateRpheqResult(rpheqVo);
            response = RestResponse.succeed(excelDataVos);
        } catch (Exception e) {
            String errorMsg = "查询失败!";
            log.error(errorMsg, e);
            response = RestResponse.fail(errorMsg);
        }
        return response;
    }

}